package com.wh.accesscontrol.config;

import com.wh.accesscontrol.util.RedisUtil;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * accesscontrol
 * 拦截类
 * @author : WH
 * @date : 2020-03-03 14:58
 *
 *
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {

@Autowired
private RedisUtil redisUtil;
    /**
     * 前处理
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @return boolean* @throws Exception 异常
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)   throws Exception {
       //解决redis无法注入问题
        if (null ==redisUtil){
            BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            redisUtil = (RedisUtil) factory.getBean("redisUtil");
        }

    //判断用户之前是否登陆
    String access_token=request.getHeader("access_token");
    Object token= redisUtil.get(access_token);

    if (token==null) {
        returnJson(response,"{\"code\":400,\"msg\":\"登陆已过期，请重新登陆！\"}");
        System.out.println("5");

        return false;
    }
    return true;
}


    /**
     * 返回Json
     *
     * @param response 响应
     * @param json     json
     * @throws Exception 异常
     */
    private void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {

        } finally {
            if (writer != null)
                writer.close();
        }
    }

}
